﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Database.Context;
using QuanLyThongTinCoSo.Common;
using Model = Database.Models;

namespace QuanLyThongTinCoSo.Biz
{
    public class RoleBiz : BaseBiz
    {
        public RoleBiz()
        {
            DbContext = new Context();
        }

        public RoleBiz(Context context)
        {
            DbContext = context;
        }

        public override void Insert(Model.BaseModel model)
        {
            var role = model as Model.Role;
            role.Created = DateTime.Now;
            role.Modified = DateTime.Now;
            role.CreatedBy = Utilities.CurrentUser();
            role.ModifiedBy = Utilities.CurrentUser();

            DbContext.Roles.Add(role);
            DbContext.SaveChanges();
        }

        public override void Update(Model.BaseModel model)
        {
            var role = model as Model.Role;
            role.Modified = DateTime.Now;
            role.ModifiedBy = Utilities.CurrentUser();

            DbContext.Entry(role).State = EntityState.Modified;
            DbContext.SaveChanges();
        }

        public override void Delete(Model.BaseModel model)
        {
            DbContext.Roles.Attach(model as Model.Role);
            DbContext.Roles.Remove(model as Model.Role);
            DbContext.Entry(model).State = EntityState.Deleted;

            DbContext.SaveChanges();
        }

        public override void DeleteItems(List<Model.BaseModel> models)
        {
            foreach (Model.Role role in models)
            {
                DbContext.Roles.Attach(role);
                DbContext.Roles.Remove(role);
                DbContext.Entry(role).State = EntityState.Deleted;
            }

            DbContext.SaveChanges();
        }

        public override Model.BaseModel GetItemById(int id)
        {
            return (from item in DbContext.Roles
                    where item.Id == id
                    select item).First();
        }

        public Model.Role GetRoleByName(string roleName)
        {
            return DbContext.Roles.FirstOrDefault(r => r.RoleName == roleName);
        }

        #region GetAll

        public List<Model.Role> GetAll()
        {
            return DbContext.Roles.OrderBy(r => r.RoleName).ToList();
        }

        #endregion
    }
}